package demo.IOStream;

import java.io.*;
import java.nio.file.Files;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/11-08-11-19:18
 * @Description：demo.IOInputOutput
 */
public class downloadFile {
    public static void main(String[] args){

        File targetFile = new File("C:\\Users\\hjy\\Pictures\\jjy2.jpg");
        File newFile = new File("D:\\qq文件\\jjy2.jpg");
        RandomAccessFile ras1 = null;
        RandomAccessFile ras2 = null;
        try {
            ras1 = new RandomAccessFile(targetFile,"r");
            ras2 = new RandomAccessFile(newFile,"rw");


            long length = ras1.length();
            int countThread = 5;
            for (int i = 0; i < countThread; i++) {
                if(i == countThread-1){
                    new copyFile(ras1,ras2,length/countThread*i,length-1).start();
                }else{
                    new copyFile(ras1,ras2,length/countThread*i,length/countThread*(i+1)).start();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
class copyFile extends Thread{
    static Object obj = new Object();
    RandomAccessFile ras1 = null;
    RandomAccessFile ras2 = null;
    long start;
    long end;

    public copyFile(RandomAccessFile ras1, RandomAccessFile ras2, long start, long end) {
        this.ras1 = ras1;
        this.ras2 = ras2;
        this.start = start;
        this.end = end;
    }

    @Override
    public void run() {
        try {

            byte[] b = new byte[1024];
            int len = -1;
            int length = 0;
            while (length < end-start) {
                synchronized (obj) {
                    ras1.seek(start + length);
                    ras2.seek(start + length);
                    len = ras1.read(b);
                    if (end - start - length < 1024 && len == 1024) {
                        ras2.write(b, 0, (int) (end - start - length));
                        break;
                    }
                    ras2.write(b, 0, len);
                    System.out.println(Thread.currentThread() + "下载了： " + len);
                    length = length + len;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}